package cn.happy.favdish.view.fragments

import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.navigation.fragment.navArgs
import androidx.palette.graphics.Palette
import cn.happy.favdish.R
import cn.happy.favdish.application.FavDishApplication
import cn.happy.favdish.databinding.FragmentDishDetailsBinding
import cn.happy.favdish.model.entities.FavDish
import cn.happy.favdish.utils.Constants
import cn.happy.favdish.view.activities.AddUpdateDishActivity
import cn.happy.favdish.view.viewmodel.FavDishViewModel
import cn.happy.favdish.view.viewmodel.FavDishViewModelFactory
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target

/**
 */
@Suppress("DEPRECATION")
class DishDetailsFragment : Fragment() {
    private var _binding: FragmentDishDetailsBinding? = null

    private val mFavDishViewModel: FavDishViewModel by viewModels {
        FavDishViewModelFactory((requireActivity().application as FavDishApplication).repository)
    }
    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private var mFavDishDetails:FavDish? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentDishDetailsBinding.inflate(inflater,container,false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments.let {
            val favDish = it?.getParcelable<FavDish>("fav_dish")
            mFavDishDetails = favDish
            if (favDish != null) {
                binding.detailTitle.text = favDish.title
                binding.typeValue.text = favDish.type
                binding.ingredientValue.text = favDish.ingredients
                binding.detailDirectionCookValue.text = favDish.directionToCook
                if(favDish.favoriteDish){
                    binding.ivFavorite.setImageDrawable(ContextCompat.getDrawable(
                        requireActivity(), R.drawable.ic_favorite_selected))
                }else{
                    binding.ivFavorite.setImageDrawable(ContextCompat.getDrawable(
                        requireActivity(), R.drawable.ic_favorite))
                }
                Glide.with(requireActivity())
                    .load(favDish.image)
                    .centerCrop()
                    .listener(object : RequestListener<Drawable>{
                        override fun onLoadFailed(
                            e: GlideException?,
                            model: Any?,
                            target: Target<Drawable>,
                            isFirstResource: Boolean
                        ): Boolean {
                            Log.e("detail image failed==","Error loading image")
                            return false
                        }

                        override fun onResourceReady(
                            resource: Drawable,
                            model: Any,
                            target: Target<Drawable>?,
                            dataSource: DataSource,
                            isFirstResource: Boolean
                        ): Boolean {
                            Palette.from(resource.toBitmap()).generate(){
                                palette ->
                                val intColor = palette?.vibrantSwatch?.rgb
                                if (intColor != null) {
                                    binding.clDishDetail.setBackgroundColor(intColor)
                                }
                            }
                            return false
                        }

                    })
                    .into(binding.detailImg)


                binding.ivFavorite.setOnClickListener{
                    favDish.favoriteDish = !favDish.favoriteDish
                    mFavDishViewModel.update(favDish)

                    if(favDish.favoriteDish){
                        binding.ivFavorite.setImageDrawable(ContextCompat.getDrawable(
                            requireActivity(), R.drawable.ic_favorite_selected))
                        Toast.makeText(requireActivity(),resources.getString(R.string.msg_added_to_favorites),Toast.LENGTH_SHORT).show()
                    }else{
                        binding.ivFavorite.setImageDrawable(ContextCompat.getDrawable(
                            requireActivity(), R.drawable.ic_favorite))
                        Toast.makeText(requireActivity(),resources.getString(R.string.msg_removed_to_favorites),Toast.LENGTH_SHORT).show()

                    }
                }

            }
        }

        // 设置菜单 分享
        requireActivity().addMenuProvider(object  : MenuProvider {
            override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
                menuInflater.inflate(R.menu.menu_share,menu)
            }

            override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
                when(menuItem.itemId){
                    R.id.action_share_dish -> {
                        // 分享
                        val type = "text/plain"
                        val subject = "Checkout this dish recipe"
                        var extraText = ""
                        val shareWith = "Share With"

                        mFavDishDetails?.let {
                            var image = ""
                            if(it.imageSource == Constants.DISH_IMAGE_SOURCE_ONLINE){
                                image = it.image
                            }

                            var cookingInstructions = Html.fromHtml(it.directionToCook,
                                Html.FROM_HTML_MODE_COMPACT).toString()

                            extraText = "$image \n" + "Title: ${it.title}\n Type: ${it.type} \n" +
                                    "Category: ${it.category} \n" +
                                    "Ingredients: ${it.ingredients} \n " +
                                    "Instructions To Cook: ${cookingInstructions} \n" +
                                    "Time required to cook the dish approx ${it.cookingTime} minutes"
                        }

                        val intent = Intent(Intent.ACTION_SEND)
                        intent.type = type
                        intent.putExtra(Intent.EXTRA_SUBJECT, subject)
                        intent.putExtra(Intent.EXTRA_TEXT, extraText)
                        startActivity(Intent.createChooser(intent, shareWith))
                    }

                }
                return true
            }
        },viewLifecycleOwner, Lifecycle.State.RESUMED)


    }
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}